﻿using System.Threading.Tasks;
using System.Linq;
using Xamarin.Forms;
using System.Collections.Generic;
using Moven.ViewModels;
using static Moven.Statics;

namespace Moven.Views
{
    public class RootPage : MasterDetailPage
    {
        public static bool IsUwpDesktop { get; set; }
        Dictionary<MenuType, NavigationPage> Pages { get; set; }

        public RootPage()
        {
            Pages = new Dictionary<MenuType, NavigationPage>();
            Master = new MenuPage(this);
            BindingContext = new BaseViewModel
            {
                Title = "墨文",
                Subtitle = "墨文",
                Icon = "slideout.png"
            };
			
            //setup home page
			NavigateAsync(MenuType.AllArticles);
			LoadArticles();

            InvalidateMeasure();
        }

        T AddPage<T>(MenuType id, T page)
            where T: ContentPage
        {
            Pages.Add(id, new MovenNavigationPage(page));
            return page;
        }

        public async Task NavigateAsync(MenuType id)
        {
            if (!Pages.ContainsKey(id))
            {
                switch (id)
                {
                    case MenuType.About:
                        AddPage(id, new AboutPage());
                        break;

                    case MenuType.AllArticles:
						AddPage(id, new ArticlesPage("所有墨文", new List<ArticleWithBookmark>(), id));
                        break;

                    case MenuType.Bookmarks:
						AddPage(id, new BookmarksPage());
                        break;

                    case MenuType.Tags:
                        AddPage(id, new TagsPage());
                        break;

                    case MenuType.Search:
                        AddPage(id, new SearchPage());
                        break;
                }
            }

            Page newPage = Pages[id];
			if (newPage == Detail)
			{
				IsPresented = false;
				return;
			}
            if (newPage == null)
                return;

            //pop to root for Windows Phone
            if (Detail != null && Device.OS == TargetPlatform.WinPhone)
            {
                await Detail.Navigation.PopToRootAsync();
            }

            Detail = newPage;

			if (!IsUwpDesktop)
			{
				IsPresented = false;
			}
        }

		async Task LoadArticles()
		{
			await Task.Delay(1);
			var articlesPage = (ArticlesPage)(Detail as MovenNavigationPage).Page;
			var articles = await ArticlesStore.GetArticlesAsync().ConfigureAwait(false);
			articlesPage.ViewModel.LoadArticles(articles.Articles.Select(ArticleWithBookmark.FromArticle).ToList());
		}
    }
}

